import { Queue } from '@/lib/Queue';
import { sizeType, IEvent } from '../index.d';
import { count, transformCount } from '../utils/count';

const useDrawLoop = (eventQueue: Queue<IEvent>, eventID: boolean[]) => {
  let stop = false;
  let node: IEvent, now, raf: number, temp, index: number;

  const run = (callback: () => void) => {
    let percent: number = 0;
    if (!stop) {
      // console.log('run', raf, eventQueue.size())
      now = Date.now();
      for(let i = 0, len = eventQueue.size(); i<len ;++i) {
        node = eventQueue.dequeue()!;
        if ( eventID[node.id] ) {
          if ( (percent = ( now - node.eventStartTime) / node.eventTime) < 1 ) {
            // 这里要抽出来封装
            draw(percent);
            // 进去节点
            eventQueue.enqueue(node);
          } else {
            if ( !node.auto ) {
              eventID[node.id] = false;
            } 
            draw(1);
            node.callback();
            if ( node.auto ) {
              setTimeout(function(node: IEvent){
                node.eventStartTime = Date.now();
                eventQueue.enqueue(node);
              }, node.delay, node)
            }           
          }
        } else {
          node.callback();
        } 

      }
    }
    callback();
  }

  const draw = (percent: number) => {
    if ( node.styleName.includes('color') ) {
  
    } else if ( ['width', 'height', 'border-radius'].some((v) => node.styleName === v)) {
      node.dom.style[node.styleName as sizeType] = count(node.timing, percent) + node.unit;
      // console.log(count(node.timing, percent), percent, node.timing.from, node.timing.to)
    } else {
      // transfrom
      if ( ['translate', 'scale', 'rotate'].some((v) => node.styleName === v) ) {

      } else {
        temp = node.dom.style['transform'] as string;
        node.dom.style['transform'] = transformCount(temp, node.styleName, count(node.timing, percent) + node.unit);
      }
    }
  }

  const loop = () => {
    raf = requestAnimationFrame(
      () => run( () => setTimeout(()=> loop(),1))
    );
  }
  console.log('start loop')
  loop();

  const stopLoop = () => {
    stop = true;
  }
  const startLoop = () => {
    stop = false;
  }

  return {
    stopLoop,
    startLoop,
  }
}

export default useDrawLoop;